home *** CD-ROM | disk | FTP | other *** search
- Path: news.rdc.puc-rio.br!usenet
- From: Paulo Eduardo Neves <neves@lmf-di.puc-rio.br>
- Newsgroups: comp.lang.c++
- Subject: Re: Class constructor usage within another class constructor problem!
- Date: Tue, 19 Mar 1996 17:57:56 -0600
- Organization: Laboratorio de Metodos Formais - PUC-Rio
- Message-ID: <314F4A04.41C6@lmf-di.puc-rio.br>
- References: <DoEv3x.IDL@latcs1.lat.oz.au>
- NNTP-Posting-Host: wittgenstein.lmf-di.puc-rio.br
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (X11; I; AIX 1)
- CC: boylesgj@lion.cs.latrobe.edu.au
-
- Gregary J Boyles wrote:
- >
- > See astericks for problems.
- >
- > // address.cpp
- >
- > #include "address.h"
- >
- > // Constructor
- > Address::Address(int ANumber,const char *AStreet,const char *ACity,int AZip)
- > {
- > Number=ANumber;
- >
- > // *******************************************************************
- > // The next two lines create objects of class String. Do these objects
- > // get placed into the Street and City members of class Address, i.e.
- > // are these lines equivelent to Address.Street=AStreet etc or have I
- > // got it wrong?
- > // *******************************************************************
- > String Street(AStreet);
- > String City(ACity);
- > Zip=AZip;
- > }
-
- When the code part of the starts it members were already created, so you
- can't call their constructors again. You MUST use a assign operation.
-
- The really best thing to do is to use the inicilizer list to instanciate
- your data members. This way :
-
- Address::Address(int ANumber,const char *AStreet,
- const char *ACity,int AZip)
- :Street(AStreet), City(ACity), Number(ANumber), Zip(AZip) {}
-
- Working thid way you code is not just more elegant, but also more
- eficient. This happens because when using the first approach you call
- the default cnst, initialise it members with a defaut value, call the
- assign operator and assign it members with the desired value. Using the
- initialiser list you just call the copy cnst and already put the desired
- values in it members. Imagine if your objects contains objects that
- contains objects that ... how many desnecessary calls are you doing.
-
- Another nice rule to follow is to always make your cnst inline when it
- has an empty body. This will ALWAYS make your programs faster.
-
- hope this helps,
- --
- Paulo Eduardo Neves Laboratorio de Metodos Formais - PUC-Rio
- mailto:neves@lmf-di.puc-rio.br Tel.: (021)512-8045
-